package cn.jobstart.service.impl;

import cn.jobstart.common.NumberUtil;
import cn.jobstart.common.SkList;
import cn.jobstart.common.SkMap;
import cn.jobstart.common.StringUtil;
import cn.jobstart.dao.ITalentSubscriptionTaskDao;
import cn.jobstart.enums.TalentSubscriptionTaskStatusEnum;
import cn.jobstart.exception.ExceptionMessage;
import cn.jobstart.model.TalentSubscriptionTask;
import cn.jobstart.modelExt.TalentSubscriptionTaskExt;
import cn.jobstart.pubInter.AbstractBaseService;
import cn.jobstart.pubInter.BaseSearch;
import cn.jobstart.pubInter.IBaseDao;
import cn.jobstart.pubInter.exception.BusinessException;
import cn.jobstart.pubInter.exception.SkException;
import cn.jobstart.searchExt.TalentSubscriptionTaskSearchExt;
import cn.jobstart.service.IAdminService;
import cn.jobstart.service.ITalentSubscriptionTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;


/**
 * @author sunke
 * @Date 2023-09-06 15:00:21
 * @description TalentSubscriptionTaskService      人才订阅任务
 */
@Service(value = "talentSubscriptionTaskService")
@Slf4j
public class TalentSubscriptionTaskServiceImpl extends AbstractBaseService<TalentSubscriptionTaskExt, TalentSubscriptionTaskSearchExt, String> implements ITalentSubscriptionTaskService {

    @Resource(name = "talentSubscriptionTaskDao")
    private ITalentSubscriptionTaskDao talentSubscriptionTaskDao;
    @Resource
    private IAdminService adminService;

    @Override
    public IBaseDao<TalentSubscriptionTaskExt, TalentSubscriptionTaskSearchExt, String> getDao() {
        return talentSubscriptionTaskDao;
    }
    private static byte[] LOCK_UPDATE_RESUME_COUNT=new byte[0];

    /**
     * 更新简历更新数量
     *
     * @param taskId
     * @param count
     */
    @Override
    public void updateResumeUpdateCountByTaskIdAndCount(String taskId, int count) {
        if (StringUtil.isNullOrEmpty(taskId) || count == 0) {
            return;
        }
        try {
            synchronized (LOCK_UPDATE_RESUME_COUNT) {
                talentSubscriptionTaskDao.updateResumeUpdateCountByTaskIdAndCount(taskId, count);
            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    /**
     * 更新爬取的总数量
     *
     * @param taskId
     * @param count
     */
    @Override
    public void updateResumeGraspCountByTaskIdAndCount(String taskId, int count) {


        if (StringUtil.isNullOrEmpty(taskId) || count == 0) {
            return;
        }
        try {
            talentSubscriptionTaskDao.updateResumeGraspCountByTaskIdAndCount(taskId, count);
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    @Override
    public void updateStatus(int status, String taskId) {
        if (StringUtil.isNullOrEmpty(taskId)) {
            return;
        }
        SkMap<String, Object> dataMap = SkMap.getInstance().addObjToMap(TalentSubscriptionTask.STATUS, status);
        if (status == TalentSubscriptionTaskStatusEnum.STOP.getType().intValue()) {
            dataMap.addObjToMap(TalentSubscriptionTask.STOP_TIME, new Date());
        }
        if (status == TalentSubscriptionTaskStatusEnum.CLOSE.getType().intValue()) {
            dataMap.addObjToMap(TalentSubscriptionTask.CLOSE_TIME, new Date());
        }


        try {
            updateDataById(dataMap, taskId);
        } catch (SkException e) {

        }


    }

    /**
     * 得到待启动列表
     *
     * @return
     * @throws SkException
     */
    @Override
    public List<TalentSubscriptionTaskExt> getWaitRunList() throws SkException {

        TalentSubscriptionTaskSearchExt search = TalentSubscriptionTaskSearchExt.getInstance();
        search.setStatusIn(SkList.getInstance().addObjToList(TalentSubscriptionTaskStatusEnum.WAIT_RUN.getType().intValue()));

        return getAllList(search);


    }


    @Override
    public TalentSubscriptionTaskExt getWaitRun() throws SkException {


        TalentSubscriptionTaskSearchExt search = TalentSubscriptionTaskSearchExt.getInstance();
        search.setStatusIn(SkList.getInstance().addObjToList(TalentSubscriptionTaskStatusEnum.WAIT_RUN.getType().intValue()));
        search.setOrderDesc(BaseSearch.ASC_ORDER);
        search.setOrderBy(TalentSubscriptionTask.CREATE_TIME);
        return getDetailBySearch(search);

    }

    /**
     * 得到在运行中的
     *
     * @return
     */
    @Override
    public TalentSubscriptionTaskExt getRunning() {
        TalentSubscriptionTaskSearchExt search = TalentSubscriptionTaskSearchExt.getInstance();
        search.setStatusIn(SkList.getInstance().addObjToList(TalentSubscriptionTaskStatusEnum.RUNNING.getType().intValue()));
        search.setOrderDesc(BaseSearch.ASC_ORDER);
        search.setOrderBy(TalentSubscriptionTask.CREATE_TIME);
        return getDetailBySearch(search);
    }

    /**
     * 启动某一订阅任务
     *
     * @param taskId
     * @param adminId
     * @param adminTruename
     * @throws SkException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void start(String taskId, String adminId, String adminTruename) throws SkException {

        if (StringUtil.isNullOrEmpty(taskId) || StringUtil.isNullOrEmpty(adminId)) {
            throw new BusinessException(ExceptionMessage.OBJECT_NULL);

        }


        TalentSubscriptionTaskExt task = getDetail(taskId, new HashSet<>());
        int status = NumberUtil.parseInt(task.getStatus());
        if (TalentSubscriptionTaskStatusEnum.isRun(status)) {
            throw new BusinessException(ExceptionMessage.ADMIN_SUBSCRIPTION_STATUS_ERROR);

        }
        adminService.addRunSubscriptionTask(adminId);
        task.setStatus(TalentSubscriptionTaskStatusEnum.WAIT_RUN.getType());
        task.setStartTime(new Date());
        update(task);

    }


    /**
     * 暂停
     *
     * @param taskId
     * @param adminId
     * @param adminTruename
     * @throws SkException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void stop(String taskId, String adminId, String adminTruename) throws SkException {

        if (StringUtil.isNullOrEmpty(taskId) || StringUtil.isNullOrEmpty(adminId)) {
            throw new BusinessException(ExceptionMessage.OBJECT_NULL);

        }

        TalentSubscriptionTaskExt task = getDetail(taskId, new HashSet<>());
        int status = NumberUtil.parseInt(task.getStatus());
        if (TalentSubscriptionTaskStatusEnum.isStop(status)) {

            throw new BusinessException(ExceptionMessage.ADMIN_SUBSCRIPTION_STATUS_ERROR);
        }

        //只有待运行的才可以暂停 ,说明爬虫还没真的运行
        if (status == TalentSubscriptionTaskStatusEnum.WAIT_RUN.getType().intValue()) {
            adminService.reduceRunSubscriptionTask(adminId);
            task.setStatus(TalentSubscriptionTaskStatusEnum.SUSPEND.getType());
            task.setSuspendTime(new Date());
            update(task);
        }


    }
}